package handler

import (
	"context"
	"gitee.com/Johnsonsmile/microshop/cart/common"
	"gitee.com/Johnsonsmile/microshop/cart/domain/model"
	"gitee.com/Johnsonsmile/microshop/cart/domain/service"
	cart "gitee.com/Johnsonsmile/microshop/cart/proto"
)

type CartHandler struct {
	CartDataService service.ICartDataService
}

func (c *CartHandler) AddCart(ctx context.Context, info *cart.CartInfo, response *cart.AddCartResponse) error {

	cartCreated := &model.Cart{}
	err := common.SwapTo(info, cartCreated)
	if err != nil {
		response.Msg = "添加购物车失败!"
		return err
	}
	cid, err := c.CartDataService.AddCart(cartCreated)
	if err != nil {
		response.Msg = "添加购物车失败!"
		return err
	}
	response.CartId = cid
	response.Msg = "添加购物车成功!"
	return nil
}

func (c *CartHandler) CleanCart(ctx context.Context, request *cart.UserIDRequest, response *cart.CartResponse) error {
	err := c.CartDataService.CleanCart(request.UserId)
	if err != nil {
		response.Msg = "清除购物车失败!"
		return err
	}
	response.Msg = "清除购物车成功!"
	return nil
}

func (c *CartHandler) Incr(ctx context.Context, info *cart.ItemInfo, response *cart.CartResponse) error {
	err := c.CartDataService.IncrNum(info.Id, info.ChangeNum)
	if err != nil {
		response.Msg = "添加数量失败!"
		return err
	}
	response.Msg = "添加数量成功!"
	return nil
}

func (c *CartHandler) Decr(ctx context.Context, info *cart.ItemInfo, response *cart.CartResponse) error {
	err := c.CartDataService.DecrNum(info.Id, info.ChangeNum)
	if err != nil {
		response.Msg = "减少数量失败!"
		return err
	}
	response.Msg = "减少数量成功!"
	return nil
}

func (c *CartHandler) DeleteItemByID(ctx context.Context, request *cart.CartIDRequest, response *cart.CartResponse) error {
	err := c.CartDataService.DeleteCart(request.CartId)
	if err != nil {
		response.Msg = "删除购物车失败!"
		return err
	}
	response.Msg = "删除购物车成功!"
	return nil
}

func (c *CartHandler) FindAll(ctx context.Context, request *cart.UserIDRequest, response *cart.CartAllResponse) error {
	carts, err := c.CartDataService.FindAllCart(request.UserId)
	if err != nil {
		return err
	}
	cartInfos := make([]*cart.CartInfo, len(carts))
	for _, c := range carts {
		cartInfo := cart.CartInfo{}
		err := common.SwapTo(c, &cartInfo)
		if err != nil {
			return err
		}
		cartInfos = append(cartInfos, &cartInfo)
	}
	response.Carts = cartInfos
	return nil
}
